function sendVerificationCode() {
    var email = document.getElementById('email').value;
    var username = document.getElementById('username').value;

    if (!email || !username) {
        document.getElementById('message').innerText = "请输入用户名和电子邮件地址";
        return;
    }

    document.getElementById('sendCodeBtn').disabled = true;

    fetch('/send_verification_code', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ email: email, username: username })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            document.getElementById('message').innerText = data.message;
            startTimer();
        } else {
            document.getElementById('message').innerText = data.message;
            document.getElementById('sendCodeBtn').disabled = false;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        document.getElementById('message').innerText = '发送验证码时出错';
        document.getElementById('sendCodeBtn').disabled = false;
    });
}

function startTimer() {
    let timeLeft = 10;
    const timer = setInterval(() => {
        if (timeLeft <= 0) {
            clearInterval(timer);
            document.getElementById('sendCodeBtn').disabled = false;
            document.getElementById('sendCodeBtn').innerText = "发送验证码";
        } else {
            document.getElementById('sendCodeBtn').innerText = `等待 ${timeLeft} 秒`;
        }
        timeLeft -= 1;
    }, 1000);
}

document.getElementById('resetPasswordForm').addEventListener('submit', function(event) {
    event.preventDefault();

    const formData = new FormData(event.target);
    const data = Object.fromEntries(formData.entries());

    fetch('/forgot_password', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            document.getElementById('message').textContent = '密码重置成功，请登录';
        } else {
            document.getElementById('message').textContent = '重置密码失败: ' + data.message;
        }
    })
    .catch(error => {
        console.error('重置密码时出错:', error);
        document.getElementById('message').textContent = '重置密码时出错，请稍后再试';
    });
});
